package com.centaline.androidsalesblog.activities;

import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.centaline.androidsalesblog.BuildConfig;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.mine.LoginActivity;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.constants.SprfConstant;
import com.centaline.androidsalesblog.events.CityInfoUpdate;
import com.centaline.androidsalesblog.events.JPushMessage;
import com.centaline.androidsalesblog.events.RongConnectStatus;
import com.centaline.androidsalesblog.events.RongReceiveMessage;
import com.centaline.androidsalesblog.events.RongTokenEvent;
import com.centaline.androidsalesblog.events.UserOperate;
import com.centaline.androidsalesblog.fragments.EntrustFragment;
import com.centaline.androidsalesblog.fragments.HomeFragment;
import com.centaline.androidsalesblog.fragments.MineFragment;
import com.centaline.androidsalesblog.fragments.NewsFragment;
import com.centaline.androidsalesblog.iml.RetryRequest;
import com.centaline.androidsalesblog.model.businissobject.AppUpdateBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.CityDo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.rx.request.RxRequest;
import com.centaline.androidsalesblog.service.BaseDataService;
import com.centaline.androidsalesblog.service.RongLoginService;
import com.centaline.androidsalesblog.utils.JPushExampleUtil;
import com.centanet.framework.model.AppUpdateProgress;
import com.centanet.framework.service.ApkDownloadService;
import com.centanet.framework.utils.AppUpdateUtil;
import com.centanet.framework.utils.SprfUtil;
import com.orhanobut.logger.Logger;
import com.trello.rxlifecycle.ActivityEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;
import java.util.Locale;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 主页面
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {

    /*UI*/
    private RelativeLayout rl_main_home, rl_main_news, rl_main_entrust, rl_main_mine;
    private HomeFragment frag_home;
    private NewsFragment frag_news;
    private EntrustFragment frag_entrust;
    private MineFragment frag_mine;
    private ImageView img_main_news_point;

    private int lastPosition = -1;//上次选中位置
    private boolean connected;
    private CityDo preCityDo;//上次选择城市
    private ProgressDialog appUpdateDialog;//app升级弹框
    private boolean appUpdateLimit;//app升级弹框限制
    private long lastBackTime;
    private boolean showPoint;

    private BaseDataService.BaseDataUpdate baseDataUpdate = new BaseDataService.BaseDataUpdate() {
        @Override
        public void update(int result) {
            if (connected) {
                connected = false;
                unbindService(baseDataConnection);
            }
            switch (result) {
                case BaseDataService.UpdateResult.Error:
                    if (preCityDo != null)
                        AppConstant.exchangeCity(MainActivity.this, preCityDo);
                    break;
                default:
                    break;
            }
            cancelLoadingDialog();
            bizUnit();
            frag_home.refreshUi(result);
            frag_mine.refreshUi();
        }
    };
    /*基础数据连接*/
    private ServiceConnection baseDataConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            connected = true;
            ((BaseDataService.BaseDataBinder) service).start(baseDataUpdate);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            connected = false;
        }
    };

    @Override
    protected void onDestroy() {
        if (connected) {
            connected = false;
            unbindService(baseDataConnection);
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void findViews() {
        rl_main_home = (RelativeLayout) findViewById(R.id.rl_main_home);
        rl_main_news = (RelativeLayout) findViewById(R.id.rl_main_news);
        rl_main_entrust = (RelativeLayout) findViewById(R.id.rl_main_entrust);
        rl_main_mine = (RelativeLayout) findViewById(R.id.rl_main_mine);

        frag_home = (HomeFragment) getSupportFragmentManager().findFragmentById(R.id.frag_home);
        frag_news = (NewsFragment) getSupportFragmentManager().findFragmentById(R.id.frag_news);
        frag_entrust = (EntrustFragment) getSupportFragmentManager().findFragmentById(R.id.frag_entrust);
        frag_mine = (MineFragment) getSupportFragmentManager().findFragmentById(R.id.frag_mine);

        img_main_news_point = (ImageView) findViewById(R.id.img_main_news_point);
    }

    @Override
    protected void initViews() {
        frag_home.setRetryRequest(new RetryRequest() {
            @Override
            public void retry() {
                bindBaseDataService();
            }
        });
        selectTab(0);
    }

    /**
     * 城市信息更新
     */
    @Subscribe
    public void onEventMainThread(CityInfoUpdate cityInfoUpdate) {
        switch (cityInfoUpdate.getStatus()) {
            case 0://强制跳转至城市列表
                //未能确定当前城市
                startActivityForResult(new Intent(MainActivity.this, CityListActivity.class)
                        .putExtra(ExtraConstant.ForceSelectCity, true), CommonConstant.REQ_EXCHANGE_CITY);
                break;
            case 1://用户切换城市
                startActivityForResult(new Intent(MainActivity.this, CityListActivity.class),
                        CommonConstant.REQ_EXCHANGE_CITY);
                break;
            case 2://更新本城市信息
                bindBaseDataService();
                break;
            case 3://版本更新
                appUpdate();
                break;
            case 4://首次进入没有模块数据
                bindBaseDataService();
                showLoadingDialog();
                break;
            default:
                break;
        }
    }

    /**
     * 绑定基础数据服务
     */
    private void bindBaseDataService() {
        bindService(new Intent(MainActivity.this, BaseDataService.class),
                baseDataConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AppConstant.IsLogin && (AppConstant.connectionStatus == null ||
                AppConstant.connectionStatus.getValue() ==
                        RongIMClient.ConnectionStatusListener.ConnectionStatus.DISCONNECTED.getValue())) {
            rongConnect();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case CommonConstant.REQ_EXCHANGE_CITY:
                    final CityDo cityDo = data.getParcelableExtra(ExtraConstant.CityDo);
                    AppConstant.exchangeCity(this, cityDo);
                    if (data.getParcelableExtra(ExtraConstant.PreCityDo) != null) {
                        preCityDo = data.getParcelableExtra(ExtraConstant.PreCityDo);
                    }
                    showLoadingDialog();
                    bindBaseDataService();
                    break;
                case CommonConstant.REQ_LOGIN:
                    selectTab(1);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_main_home:
                selectTab(0);
                break;
            case R.id.rl_main_news:
                if (AppConstant.IsLogin) {
                    selectTab(1);
                } else {
                    startActivityForResult(new Intent(this, LoginActivity.class), CommonConstant.REQ_LOGIN);
                }
                break;
            case R.id.rl_main_entrust:
                selectTab(2);
                break;
            case R.id.rl_main_mine:
                selectTab(3);
                break;
            default:
                break;
        }
    }

    /**
     * 选中标签
     *
     * @param position 位置0-3
     */
    private void selectTab(final int position) {
        switch (lastPosition) {
            case 0:
                rl_main_home.setEnabled(true);
                hideFragment(frag_home);
                break;
            case 1:
                rl_main_news.setEnabled(true);
                hideFragment(frag_news);
                break;
            case 2:
                rl_main_entrust.setEnabled(true);
                hideFragment(frag_entrust);
                break;
            case 3:
                rl_main_mine.setEnabled(true);
                hideFragment(frag_mine);
                break;
            default:
                hideFragment(frag_news);
                hideFragment(frag_entrust);
                hideFragment(frag_mine);
                break;
        }
        lastPosition = position;
        switch (position) {
            case 0:
                rl_main_home.setEnabled(false);
                showFragment(frag_home);
                break;
            case 1:
                rl_main_news.setEnabled(false);
                showFragment(frag_news);
                break;
            case 2:
                rl_main_entrust.setEnabled(false);
                showFragment(frag_entrust);
                break;
            case 3:
                rl_main_mine.setEnabled(false);
                showFragment(frag_mine);
                break;
            default:
                rl_main_home.setEnabled(false);
                showFragment(frag_home);
                break;
        }
    }

    /**
     * 隐藏Fragment
     */
    private void hideFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().hide(fragment).commit();
    }

    /**
     * 显示Fragment
     */
    private void showFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().show(fragment).commit();
    }


    /**
     * 用户状态操作
     */
    @Subscribe
    public void onEventMainThread(UserOperate userOperate) {
        switch (userOperate.getStatus()) {
            case 0://退出
                SprfUtil.setInt(this,
                        String.format("%s_%s", SprfConstant.COLLECT_POSITION, AppConstant.CityCode), 11);
                setJPushAlias();
                if (RongIMClient.getInstance() != null) {
                    RongIMClient.getInstance().clearConversations(
                            new RongIMClient.ResultCallback() {
                                @Override
                                public void onSuccess(Object o) {
                                    RongIMClient.getInstance().logout();
                                }

                                @Override
                                public void onError(RongIMClient.ErrorCode errorCode) {
                                    RongIMClient.getInstance().logout();
                                }
                            }, Conversation.ConversationType.PRIVATE
                    );
                }
                showPoint();
                break;
            case 1://登录
                setJPushAlias();
                rongToken();
                break;
            case 2://用户
                break;
            default:
                break;
        }
    }

    private void setJPushAlias() {
        JPushExampleUtil.setAlias(getApplicationContext());
    }

    /**
     * 融云token获取
     */
    @Subscribe
    public void onEventMainThread(RongTokenEvent rongTokenEvent) {
        switch (rongTokenEvent.getStatus()) {
            case 0://成功
                rongConnect();
                break;
            case 1://网络错误

                break;
            case 2://其他错误

                break;
            default:
                break;
        }
    }

    /**
     * 融云token获取
     */
    private void rongToken() {
        startService(new Intent(MainActivity.this, RongLoginService.class));
    }

    /**
     * 融云连接
     */
    private void rongConnect() {
        RongIMClient.connect(SprfUtil.getString(this, SprfConstant.RONG_TOKEN, ""), connectCallback);
    }

    /**
     * 连接回调
     */
    RongIMClient.ConnectCallback connectCallback = new RongIMClient.ConnectCallback() {
        @Override
        public void onTokenIncorrect() {
            Logger.d("onTokenIncorrect");
            rongToken();
        }

        @Override
        public void onSuccess(String s) {
            Logger.d("onSuccess : %s", s);
            EventBus.getDefault().post(new RongConnectStatus(0));
        }

        @Override
        public void onError(RongIMClient.ErrorCode errorCode) {
            Logger.d("onError : %s", errorCode.getMessage());
            EventBus.getDefault().post(new RongConnectStatus(1));
        }
    };

    /**
     * 新通知
     */
    @Subscribe
    public void onEventMainThread(JPushMessage jPushMessage) {
        if (jPushMessage != null) {
            showPoint();
        }
    }

    /**
     * 新消息
     */
    @Subscribe
    public void onEventMainThread(RongReceiveMessage receiveMessage) {
        if (receiveMessage != null &&
                receiveMessage.getMessage() != null) {
            showPoint();
        }
    }

    private void showPoint() {
        showPoint = SprfUtil.getBoolean(this, String.format(Locale.CHINA, "%s_%s", AppConstant.CityCode, SprfConstant.JPUSH_NEW_MESSAGE), false);
        if (!showPoint &&
                AppConstant.IsLogin &&
                RongIMClient.getInstance() != null) {
            RongIMClient.getInstance().getConversationList(new RongIMClient
                    .ResultCallback<List<Conversation>>() {
                @Override
                public void onSuccess(List<Conversation> conversations) {
                    if (conversations != null) {
                        for (Conversation conversation : conversations) {
                            if (conversation.getUnreadMessageCount() > 0 &&
                                    conversation.getTargetId().contains(AppConstant.CityCode)) {//只保留当前城市的
                                showPoint = true;
                                break;
                            }
                        }
                    }
                    img_main_news_point.setVisibility(showPoint ? View.VISIBLE : View.INVISIBLE);
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                }
            }, Conversation.ConversationType.PRIVATE);
        } else {
            img_main_news_point.setVisibility(showPoint && AppConstant.IsLogin ? View.VISIBLE : View.INVISIBLE);
        }
    }


    /**
     * app 升级
     */
    @Subscribe
    public void onEventMainThread(AppUpdateProgress appUpdateProgress) {
        if (appUpdateDialog != null) {
            switch (appUpdateProgress.getStatus()) {
                case 0:
                    appUpdateDialog.dismiss();
                    finish();
                    break;
                case 1:
                    appUpdateDialog.setProgress(appUpdateProgress.getProgress());
                    break;
                case 2:
                    appUpdateDialog.dismiss();
                    toast("下载失败,请检查您的网络!");
                    finish();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * app 升级检查
     */
    private void appUpdate() {
        RxRequest.appUpdate(MainActivity.class)
                .compose(this.<AppUpdateBo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<AppUpdateBo>() {
                    @Override
                    public void call(AppUpdateBo appUpdateBo) {
                        if (appUpdateBo.getAndroidVerCode() > BuildConfig.VERSION_CODE) {
                            AppUpdateUtil.setUpdateUrl(MainActivity.this, appUpdateBo.getAndroidUrl());
                            AppUpdateUtil.setUpdateVerisonCode(MainActivity.this, appUpdateBo.getAndroidVerCode());
                            if (!appUpdateLimit &&
                                    appUpdateBo.getAndroidVerCode() - BuildConfig.VERSION_CODE > appUpdateBo.getAndroidLimit()) {
                                //强制升级
                                appUpdateLimit = true;
                                new AlertDialog.Builder(MainActivity.this)
                                        .setTitle(R.string.app_update_title)
                                        .setMessage(appUpdateBo.getAndroidMessage())
                                        .setCancelable(false)
                                        .setPositiveButton(R.string.app_update_positive, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                appUpdateLimit = false;
                                                startService(new Intent(MainActivity.this, ApkDownloadService.class));
                                                appUpdateDialog = new ProgressDialog(MainActivity.this);
                                                appUpdateDialog.setTitle(R.string.app_update_title);
                                                appUpdateDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                                appUpdateDialog.setIndeterminate(false);
                                                appUpdateDialog.setMax(100);
                                                appUpdateDialog.setProgress(0);
                                                appUpdateDialog.setCancelable(false);
                                                appUpdateDialog.show();
                                            }
                                        }).create().show();
                            } else if (!appUpdateLimit) {
                                //提示升级
                                appUpdateLimit = true;
                                new AlertDialog.Builder(MainActivity.this)
                                        .setTitle(R.string.app_update_title)
                                        .setMessage(appUpdateBo.getAndroidMessage())
                                        .setPositiveButton(R.string.app_update_positive, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                startService(new Intent(MainActivity.this, ApkDownloadService.class));
                                            }
                                        })
                                        .setNegativeButton(R.string.app_update_negative, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                appUpdateLimit = false;
                                            }
                                        })
                                        .create().show();
                            }
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }

    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        setJPushAlias();
                        showPoint();
                        frag_news.cityChange();
                        AppConstant.ShowTalk = bizUnitDo.isShowTalk();
                        rl_main_entrust.setVisibility(bizUnitDo.isEnableErshoufang() ? View.VISIBLE : View.GONE);
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            long now = System.currentTimeMillis();
            if (now - lastBackTime < 3000) {
                return super.onKeyDown(keyCode, event);
            } else {
                lastBackTime = now;
                toast("再按一次退出中原找房");
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
